package cn.xiaobai.j2exe.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.xiaobai.j2exe.AbstractApplication;
import cn.xiaobai.j2exe.consts.SysType;
import cn.xiaobai.j2exe.domain.J2ExeConfig;
import cn.xiaobai.j2exe.utils.DialogUtils;
import cn.xiaobai.j2exe.utils.FileUtils;
import cn.xiaobai.j2exe.utils.SourceUtils;
import cn.xiaobai.j2exe.utils.SysUtils;
import com.badlogicgames.packr.PackrConfig;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;

import java.io.File;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;

import static cn.xiaobai.j2exe.consts.SysType.*;

/**
 * exe 配置
 *
 * @Author yangdaji
 * @Date 2023/12/26
 * @PackageName cn.xiaobai.j2exe.view
 * @ClassName ExeConfigView
 */
public class ExeConfigController extends AbstractApplication {


    /**
     * 平台选择
     */
    @FXML
    private ChoiceBox<String> platform_select;

    /**
     * 执行名称定义
     */
    @FXML
    private TextField executable_name;

    /**
     * 输出目录
     */
    @FXML
    private TextField output_dir;

//    /**
//     * 目录选择按钮
//     */
//    @FXML
//    private Button select_bt;

    @FXML
    private Button resource_add_bt;

    @FXML
    private Button resource_del_bt;

    @FXML
    private ListView<String> resource_list;

    private ObservableList<String> resourceList = FXCollections.observableArrayList();

    @FXML
    private AnchorPane exe_conf_pane;

    private J2ExeConfig j2ExeConfig = new J2ExeConfig();

    private static String delItemValue;


    // 功能处理

    @FXML
    public void on_resource_add_click() {
        fileChooser.setTitle("选择一个资源");
        File file = fileChooser.showOpenDialog(exe_conf_pane.getScene().getWindow());
        if (FileUtil.isEmpty(file)) {
            return;
        }

        String absolutePath = FileUtils.reversPath(file);
        resourceList.add(absolutePath);
        globalConvertConfig.addResources(file);

        // 这里同时记录该位置即可
        File initialDirectory = fileChooser.getInitialDirectory();
        if (!Objects.equals(absolutePath, FileUtils.reversPath(initialDirectory))) {
            fileChooser.setInitialDirectory(file.getParentFile());
        }
    }

    @FXML
    public void on_resource_del_click() {
        // 删除
        if (delItemValue != null) {
            Iterator<File> iterator = globalConvertConfig.getResources().iterator();
            while (iterator.hasNext()) {
                File next = iterator.next();
                if (FileUtil.isNotEmpty(next)) {
                    if (FileUtils.reversPath(next).equals(delItemValue)) {
                        iterator.remove();
                    }
                }
            }
            resourceList.remove(delItemValue);
        }
    }


    /**
     * 平台选择
     */
    public void on_select_click() {
        String value = platform_select.getValue();
        globalConvertConfig.setPlatform(StrUtil.isNotBlank(value) ? value : null);
    }

    /**
     * 执行名称输入
     */
    public void exe_name_input() {
        String text = executable_name.getText();
        globalConvertConfig.setExecutable(StrUtil.isNotBlank(text) ? text : null);
    }

    /**
     * 输出目录输入
     */
    public void outputDir_input() {
        String dirText = output_dir.getText();
        if (StrUtil.isNotBlank(dirText)) {
            File outputDir = new File(FileUtils.reversPath(dirText));
            if (!outputDir.exists()) {
                outputDir = new File(j2ExeConfig.getDefaultOutPrefix(), outputDir.getPath());
            }
            globalConvertConfig.setOutDir(outputDir);
        } else {
            globalConvertConfig.setOutDir(null);
        }
    }

    /**
     * 输出目录选择
     */
    @FXML
    public void on_chooser_click() {

        directoryChooser.setTitle("选择输出目录");
        File outputDir = directoryChooser.showDialog(exe_conf_pane.getScene().getWindow());
        // 选择一个输出目录, 目录必须为空, 否则提示, 然后设置给全局转换数据
        if (outputDir == null) {
            return;
        }

        if (FileUtil.isEmpty(outputDir)) {
            globalConvertConfig.setOutDir(outputDir);
            output_dir.setText(FileUtils.reversPath(outputDir));
            updateInitDir();
        } else {
            DialogUtils.popUp("警告",outputDir + "目录不为空");
        }
    }

    @Override
    protected void refresh() {

        List<String> sourceList = globalConvertConfig.getResources()
                .stream().map(FileUtils::reversPath).toList();
        resourceList.clear();
        resourceList.addAll(sourceList);
        platform_select.setValue(SysType.toType(globalConvertConfig.getPlatform()));
        executable_name.setText(globalConvertConfig.getExecutable());
        output_dir.setText(FileUtils.reversPath(globalConvertConfig.getOutDir()));

        j2ExeConfig = SourceUtils.getAppCfg(j2ExeConfig.getClass());
    }

    @Override
    protected void updateInitDir() {
        // 输出目录
        File outputDirCache = globalConvertConfig.getOutDir();
        if (FileUtil.exist(outputDirCache) &&
                !Objects.equals(outputDirCache, directoryChooser.getInitialDirectory())) {
            directoryChooser.setInitialDirectory(outputDirCache);
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        addListener(this);
        // 初始化系统类型选择
        initSys();
        changeListener();
        initIcon();

        // 刷新数据
        refresh();

    }

    /**
     * 初始化系统类型选项
     */
    private void initSys() {

        PackrConfig.Platform platform = globalConvertConfig.getPlatform();
        if (platform != null) {
            platform_select.setValue(platform.name());
        } else {
            String osType = SysUtils.getOsType();
            if (StrUtil.isNotBlank(osType)) {
                platform_select.setValue(osType);
            }
        }
        platform_select.getItems().addAll(Windows64.getDesc(),
                Linux64.getDesc(), MacOS.getDesc());

        globalConvertConfig.setPlatform(platform_select.getValue());
    }

    /**
     * 添加监听器
     */
    private void changeListener() {
        resource_list.setItems(resourceList);
        platform_select.getSelectionModel().selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> on_select_click());

        executable_name.focusedProperty()
                .addListener((observable, oldValue, newValue) -> exe_name_input());

        output_dir.focusedProperty()
                .addListener((observable, oldValue, newValue) -> outputDir_input());

        resource_list.getSelectionModel().selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    delItemValue = newValue;
                });
    }

    private void initIcon() {
        resource_add_bt.setGraphic(new ImageView(SourceUtils.getPngImg("add-20.png")));
        resource_del_bt.setGraphic(new ImageView(SourceUtils.getPngImg("del-20.png")));
    }

}
